package cn.lili.security;

import cn.lili.cache.Cache;
import cn.lili.common.properties.IgnoredUrlsProperties;
import cn.lili.common.security.CustomAccessDeniedHandler;
import cn.lili.modules.member.service.ClerkService;
import cn.lili.modules.member.service.StoreMenuRoleService;
import cn.lili.modules.member.token.StoreTokenGenerate;
import cn.lili.modules.permission.service.MenuService;
import cn.lili.modules.system.token.ManagerTokenGenerate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfigurationSource;

/**
 * spring Security 核心配置类 Manager安全配置中心
 *
 * @author Chopper
 * @since 2020/11/14 16:20
 */
@Slf4j
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public MenuService menuService;

    @Autowired
    private Cache<String> cache;

    @Autowired
    private ManagerTokenGenerate managerTokenGenerate;

    @Autowired
    private StoreTokenGenerate storeTokenGenerate;

    @Autowired
    private StoreMenuRoleService storeMenuRoleService;

    @Autowired
    private ClerkService clerkService;

    /**
     * 忽略验权配置
     */
    @Autowired
    private IgnoredUrlsProperties ignoredUrlsProperties;
    /**
     * spring security -》 权限不足处理
     */
    @Autowired
    private CustomAccessDeniedHandler accessDeniedHandler;

    @Autowired
    private CorsConfigurationSource corsConfigurationSource;


    // 1. 先声明认证管理器Bean（解决依赖关系）
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    // 2. 声明带依赖的过滤器Bean
    @Bean
    public ManagerAuthenticationFilter managerAuthenticationFilter() throws Exception {
        return new ManagerAuthenticationFilter(authenticationManagerBean(), menuService, managerTokenGenerate, cache);
    }

    @Bean
    public BuyerAuthenticationFilter buyerAuthenticationFilter() throws Exception {
        return new BuyerAuthenticationFilter(authenticationManagerBean(), cache);
    }

    @Bean
    public StoreAuthenticationFilter storeAuthenticationFilter() throws Exception {
        return new StoreAuthenticationFilter(authenticationManagerBean(), storeTokenGenerate, storeMenuRoleService, clerkService, cache);
    }

    // 3. 使用工厂方式创建路由过滤器
//    @Bean
//    public FilterRegistrationBean<AuthenticationRouterFilter> authenticationRouterFilter(
//            ManagerAuthenticationFilter managerAuthenticationFilter,
//            BuyerAuthenticationFilter buyerAuthenticationFilter,
//            StoreAuthenticationFilter storeAuthenticationFilter
//    ) {
//        //return new AuthenticationRouterFilter(managerAuthenticationFilter, buyerAuthenticationFilter, storeAuthenticationFilter);
//        FilterRegistrationBean<AuthenticationRouterFilter> bean = new FilterRegistrationBean<>();
//        bean.setFilter(new AuthenticationRouterFilter(managerAuthenticationFilter, buyerAuthenticationFilter, storeAuthenticationFilter));
//        bean.setEnabled(false); // 不要由Servlet容器管理
//        return bean;
//    }
    @Bean
    public AuthenticationRouterFilter authenticationRouterFilter(
            ManagerAuthenticationFilter managerAuthenticationFilter,
            BuyerAuthenticationFilter buyerAuthenticationFilter,
            StoreAuthenticationFilter storeAuthenticationFilter
    ) {
        return new AuthenticationRouterFilter(
                managerAuthenticationFilter,
                buyerAuthenticationFilter,
                storeAuthenticationFilter
        );
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http
                .authorizeRequests();
        //配置的url 不需要授权
        for (String url : ignoredUrlsProperties.getUrls()) {
            registry.antMatchers(url).permitAll();
        }
        // common请求全部放行，原common-api逻辑
        registry.antMatchers("/common/**").permitAll();
        registry
                .and()
                //禁止网页iframe
                .headers().frameOptions().disable()
                .and()
                .authorizeRequests()
                //任何请求
                .anyRequest()
                //需要身份认证
                .authenticated()
                .and()
                .addFilterBefore(authenticationRouterFilter(
                        managerAuthenticationFilter(),
                        buyerAuthenticationFilter(),
                        storeAuthenticationFilter()
                ), UsernamePasswordAuthenticationFilter.class)
                //允许跨域
                .cors().configurationSource(corsConfigurationSource).and()
                //关闭跨站请求防护
                .csrf().disable()
                //前后端分离采用JWT 不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //自定义权限拒绝处理类
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler);

    }

}
